package edcom.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ImageViewer {

	private FlexTable imageList;
	private RootPanel imageViewer;
	TaggedImage[] images = null;

	/*
	 * we use this servlet "port" to acess the database
	 */
	private ImageServiceAsync imageSVC = GWT.create(ImageService.class);

	public ImageViewer(RootPanel src) {

		/*
		 * assign the div element
		 */
		imageViewer = src;

		/*
		 * this is the container for the images
		 */
		imageList = new FlexTable();
		imageViewer.add(imageList, 0, 0);

		/*
		 * check if cookies are enabled
		 */
		if(Cookies.isCookieEnabled()) {
			/* 
			 * cookie invoked by the LogBox widget 
			 */
			String usertype = Cookies.getCookie("usertype");

			/* 
			 * first invoked from a query string, then set to a cookie by a JSP 
			 * block (see ImageViewer.jsp)
			 */
			String className = Cookies.getCookie("classid");  

			getImageList(usertype, className);
		} else {
			/*
			 * show that we need cookies
			 */
			Window.alert("Please enable your browser's cookies to see the " +
			"contents properly.");
		}

		/*

		Cookies.setCookie("hello", "work!", null, null, "/", false);
		// cookie:
		// 	name: hello
		// 	value: "work!"
		// 	expiration: "When I close my browser"
		// 	domain: localhost
		// 	path: \
		// 	use SSL: no
		Window.alert(Cookies.getCookie("hello"));

		// */
	}

	/**
	 * 
	 */
	private void getImageList(String usertype, String classid) {

		// set up the service
		AsyncCallback<TaggedImage[]> callback = null; 
		if(usertype == "admin"){
			callback = new AsyncCallback<TaggedImage[]>() {
				public void onFailure(Throwable caught) {
					Window.alert("ERROR: " + caught.getMessage());
					fillTable(null, "admin"); /*
					setImagesList(null); //*/
				}

				public void onSuccess(TaggedImage[] result) {
					fillTable(result, "admin"); /*
					setImagesList(result); // */
				}
			};
		} else if(usertype == "user") {
			callback = new AsyncCallback<TaggedImage[]>() {
				public void onFailure(Throwable caught) {
					Window.alert("ERROR: " + caught.getMessage());
					fillTable(null, "user"); /*
					setImagesList(null); //*/
				}

				public void onSuccess(TaggedImage[] result) {
					fillTable(result, "user"); /*
					setImagesList(result); // */
				}
			};
		} else {
			callback = new AsyncCallback<TaggedImage[]>() {
				public void onFailure(Throwable caught) {
					Window.alert("ERROR: " + caught.getMessage());
					fillTable(null, null); /*
					setImagesList(null); //*/
				}

				public void onSuccess(TaggedImage[] result) {
					fillTable(result, null); /*
					setImagesList(result); // */
				}
			};
		}

		/*
		 * call the method
		 */
		imageSVC.getImagesFromServer(classid, callback);
	}

	private void fillTable(TaggedImage[] src, String usertype) {

		if(src == null) {
			imageList.setWidget(0, 0, new Label("There is nothing to be shown."));
		}
		else {

			/*
			 * generate a table row for every TaggedImage instance
			 */
			for(int i = 0; i < src.length; i++) {
				final String id = src[i].getId();
				final String name = src[i].getName();
				final String description = src[i].getDescription();
				final String className = src[i].getClassName();
				final String extension = src[i].getExtension();

				final String url = "images/" + id + src[i].getExtension();

				/*
				 * setup the clickable image
				 */
				Image tempImage = new Image(url);
				tempImage.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent event) {
						/*
						 * invoke and show a ImageWindow instance when clicked
						 */
						new ImageWindow().show(url, name, description);
					}
				});
				tempImage.addStyleName("gwt-ClickableImage");
				imageList.setWidget(i, 0, tempImage);
				tempImage.setWidth("100px");

				VerticalPanel tempPanel = new VerticalPanel();

				/*
				 * only show the "Erase this image" button when the user is an 
				 * admin, must reload the page first in tandem with a LogBox
				 * instance
				 */
				if(usertype == "admin"){
					Button eraseButton = new Button("Erase this image");
					eraseButton.addClickHandler(new ClickHandler() {
						public void onClick(ClickEvent event) {
							if(!Cookies.getCookie("usertype").equals("admin")) {
								Window.alert("You must be a system administrator to do that!");
							} else {
								/*
								 * this button invokes an RPC to delete the image  
								 */
								deleteImage(new TaggedImage(id, extension, 
										className, name, description));
							}
						}
					});
					eraseButton.setStyleName("gwt-ButtonEXT");
					tempPanel.add(eraseButton);
				}

				/*
				 * put the static text as info to the nearby image
				 */
				tempPanel.add(new Label(name));
				tempPanel.add(new Label(description));

				/*
				 * add the panel
				 */
				imageList.setWidget(i, 1, tempPanel);

				// TODO put comments widget

				/*
				 * align the table cells for neatness
				 */
				imageList.getCellFormatter().setVerticalAlignment(i, 0, 
						HasVerticalAlignment.ALIGN_TOP);
				imageList.getCellFormatter().setVerticalAlignment(i, 1, 
						HasVerticalAlignment.ALIGN_TOP);
			}

		}

		//		Window.alert(usertype);

	}

	protected void deleteImage(TaggedImage img) {

		AsyncCallback<String> callback = new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				Window.alert("Failed to delete image. Please retry later.");
			}

			public void onSuccess(String result) {
				if(!result.contains("ERROR")) {
					Window.alert("Image has been deleted.");
//					Window.alert(result);
//					imageViewer.clear();

//					String usertype = Cookies.getCookie("usertype");
//					String className = Cookies.getCookie("classid");  
//					getImageList(usertype, className);
					
					Window.Location.reload();
				}
				else {
					Window.alert("Failed to delete image. Please retry " +
					"later.");
				}
			}

		};

		if(Window.confirm("Do you really want to delete \"" + img.getName() + 
		"\"?" )) {
			imageSVC.deleteImage(img, null, callback);
		} else {
			// no operation
		}
	}

}
